package cn.itsource.org.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageResult;
import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/dept")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;


    //@RequestMapping(value = "/saveorUpdate",method = RequestMethod.PUT)
    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Department department) {
        try {
            if (department.getId()!=null) {
                departmentService.update(department);
            } else {
                departmentService.save(department);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().setMessage(e.getMessage());
        }
        return new AjaxResult();
    }

    //@RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            departmentService.remove(id); //如果没有异常则删除
        } catch (Exception e) {
            e.printStackTrace();
            return ajaxResult.setMessage(e.getMessage()); //如果有异常则捕获
        }
        return ajaxResult;
    }


    //@RequestMapping(value = "/findAll",method = RequestMethod.GET)
    @GetMapping
    public List<Department> findAll(){

        return departmentService.findAll();
    }

    @PostMapping   // @RequestBody  从请求体重获取参数封装到此对象中
    public PageResult<Department> findAll(    @RequestBody DepartmentQuery query){

        return departmentService.queryPage(query);
    }

    @PatchMapping
    public AjaxResult detelePatch(@RequestBody  List<Long> ids){
        try {
            departmentService.removes(ids);
        } catch (Exception e) {
            return new AjaxResult(e.getMessage());
        }
        return new AjaxResult();
    }
}
